package com.codes.core.common.thread.pool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @Description 
 * @Date 2020/8/26 10:20
 * @Created  peanut
 */
//@Configuration
//@EnableAsync
public class AsyncConfig {


    private PrimaryAsyncConstants primaryAsyncConstants;

    private SecondaryAsyncConstants secondaryAsyncConstants;

    @Autowired
    public AsyncConfig(PrimaryAsyncConstants primaryAsyncConstants, SecondaryAsyncConstants secondaryAsyncConstants) {
        this.primaryAsyncConstants = primaryAsyncConstants;
        this.secondaryAsyncConstants = secondaryAsyncConstants;
    }

    @Bean(name = "primaryExecutor")
    public Executor getPrimaryExecutor() {
        return initExecutor(primaryAsyncConstants, "PrimaryExecutor-");
    }

    @Bean(name = "secondaryExecutor")
    public Executor getSecondaryExecutor() {
        return initExecutor(secondaryAsyncConstants, "SecondaryExecutor-");
    }

    private ThreadPoolTaskExecutor initExecutor(AsyncConstants constants, String prefix) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(constants.getCorePoolSize());
        executor.setMaxPoolSize(constants.getMaxPoolSize());
        executor.setKeepAliveSeconds(constants.getKeepAliveSeconds());
        executor.setQueueCapacity(constants.getQueueCapacity());
        executor.setThreadNamePrefix(prefix);
        return executor;
    }
}